var bFiterSpeed = true;
var bFiterLocation = true;
var htmlHistorySearch = '<header id="header" class="mui-bar mui-bar-nav">' +
	'	<h1 class="mui-title" datalang="HistoryPlay">{0}</h1>' +
	'</header>' +
	'<div id="divHistorySearch" class="mui-content" style="height: 100%;">' +
	'	<div style="height: 100%; position: absolute; top:0px; width: 100%; overflow-x: hidden; overflow-y: auto;">' +
	'		<h6 class="mui-content-padded"><label datalang="Plate">{1}</label></h6>' +
	'		<input id="txtHistoryPlate" tag="" readonly="readonly" onclick="OpenHistoryPlateSearch()" type="text" class="mui-input-clear mui-input" placeholder="{2}">' +
	'		<h6 class="mui-content-padded"><label datalang="BeginTime">{3}</label></h6>' +
	'		<button class="historyTimeBtn" id="dtHistoryBeginTime" style="font-size: 18px; width:100%; height: 40px;" data-options=\'{\"value\":\"{4}\"}\' >{5}</button>' +
	'			<h6 class="mui-content-padded"><label datalang="EndTime">{6}</label></h6>' +
	'		<button class="historyTimeBtn" id="dtHistoryEndTime" style="font-size: 18px; width:100%; height: 40px;" data-options=\'{\"value\":\"{7}\"}\' datalang="EndTime" >{8}</button>' +
	'       <h6 class="mui-content-padded"><label datalang="EndTime">{9}</label></h6>' +
	'		<form class="mui-input-group">' +
	'			<ul class="mui-table-view mui-table-view-chevron">' +
	'				<li class="mui-table-view-cell">' +
	'					{10}' +
	'					<div id="divHistorySpeed" class="mui-switch {11}">' +
	'						<div class="mui-switch-handle"></div>' +
	'					</div>' +
	'				</li>' +
	'				<li class="mui-table-view-cell">' +
	'					{12}' +
	'					<div id="divHistoryLocate" class="mui-switch {13}">' +
	'						<div class="mui-switch-handle"></div>' +
	'					</div>' +
	'				</li>' +
	'			</ul>' +
	'		</form>' +
	'		<div class="mui-content-padded">' +
	'		<button id="btnHistoryQuery" class="mui-btn mui-btn-block mui-btn-primary" datalang="Query">{14}</button>' +
	'	</div>'; +
'</div>';

function selectHistoryPlateChange(name, rows, bChecked) {
	if (!bChecked) {
		$('#txtHistoryPlate').attr("tag", "");
		$('#txtHistoryPlate').val("");
		return;
	}
	$.each(rows, function(i, value) {
		$('#txtHistoryPlate').attr("tag", value["id"]);
		$('#txtHistoryPlate').val(value["name"]);
	});
}


function QueryHistory(id, sBegin, sEnd, iSpeed, iLoaction) {
	if (arrHistoryBaiduLineDs != undefined) {
		arrHistoryBaiduLineDs.set([]);
	}
	if (arrHistoryBaiduOnlineIconDs != undefined) {
		arrHistoryBaiduOnlineIconDs.set([]);
	}
	bFiterSpeed = iSpeed == 1;
	bFiterLocation = iLoaction == 1;
	var dataHistory = new Array();
	var myDate = new Date();
	/* var sHtml = String.format(htmlHistorySearch, arrLang["HistoryPlay"], arrLang["Plate"], arrLang["SearchFilter"],
		arrLang["BeginTime"], formatterSearch(myDate, "00:00"), formatterSearch(myDate, "00:00"), arrLang["EndTime"],
		formatterSearch(myDate, "23:59"), formatterSearch(myDate, "23:59"), arrLang["Filter"], arrLang["Speed"], (bFiterSpeed ? "mui-active": ""), arrLang["Location"], (bFiterLocation ? "mui-active" : ""), arrLang["Query"]);
	$('#tabbar-details').html(sHtml); */
	
	OpenHistory(id, sBegin, sEnd, iSpeed, iLoaction);
	function OpenHistory(VehID, sBegin, sEnd, iSpeed, iLoaction) {
		//轨迹查询
		var dtTime1 = new Date();
		var dtTime2 = new Date();
		var TotalDay = 0;
		var bDrawLine = false;
		var bQuery = false;
		var loadingFlag;
		OpenHistoryQuery();
		
		function DisabledBtn(bDisable){
			if(bDisable){
				$('#btnHistoryQuery').addClass("layui-btn-disabled").attr("disabled",true);
			}
			else{
				$('#btnHistoryQuery').removeClass("layui-btn-disabled").attr("disabled",false);
			}
		}

		function OpenLoding(sText) {
			/* layer.alert(sText, {
				title: arrLang.Tips
			}) */
			loadingFlag= layer.msg(sText, { icon: 16, shade: 0.01,shadeClose:false,time:600000 });
		}

		function Query() {
			if (timePlay != undefined) {
				clearTimeout(timePlay);
				timePlay = undefined;
			}
			bDrawLine = false;
			dataHistory.length = 0;
			var dtBegin = new Date(sBegin.replace(/-/g, "/"));
			var dtEnd = new Date(sEnd.replace(/-/g, "/"));
			var date3 = dtEnd.getTime() - dtBegin.getTime();
			//计算出相差天数
			TotalDay = Math.floor(date3 / (24 * 3600 * 1000));
			dtTime1 = new Date();
			if (true) {
				var nextData = new Date(dtBegin);
				nextData.setDate(nextData.getDate() + 1);
				var y = nextData.getFullYear();
				var m = nextData.getMonth() + 1;
				var d = nextData.getDate();
				var sTime1 = y + "/" + (m < 10 ? ('0' + m) : m) + '/' + (d < 10 ? ('0' + d) : d) + " 00:00:01";
				dtTime1 = new Date(sTime1);
			}
			dtTime2 = dtEnd;
			var sUserType = "2";
			//            if(bUserID)
			//            {
			//                sUserType = "1";
			//            }
			if (isNaN(dtBegin)) {
				DisabledBtn(false);
				AjaxErro(arrLang["BeginTime"] + " " + arrLang["ParErr"]);
				return;
			}
			if (isNaN(dtEnd)) {
				DisabledBtn(false);
				AjaxErro(arrLang["EndTime"] + " " + arrLang["ParErr"]);
				return;
			}
			if (dtBegin > dtEnd) {
				DisabledBtn(false);
				AjaxErro(arrLang["Time"] + " " + arrLang["ParErr"]);
				return;
			}
			bQuery = false;
			var sQueryTime1 = "";
			var sQueryTime2 = "";
			var sUrl = app.getAppUrl().url;
			if (dtBegin.getFullYear() != dtEnd.getFullYear()) //年不相同
			{
				var y = dtBegin.getFullYear();
				var m = dtBegin.getMonth() + 1;
				var d = dtBegin.getDate();
				var sTimeEnd = y + "-" + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " 23:59:59";
				sQueryTime1 = formatterTime(dtBegin);
				sQueryTime2 = sTimeEnd;
				bQuery = true;
				OpenLoding("1%");
			} else if (dtBegin.getMonth() != dtEnd.getMonth()) //月不相同
			{
				var y = dtBegin.getFullYear();
				var m = dtBegin.getMonth() + 1;
				var d = dtBegin.getDate();
				var sTimeEnd = y + "-" + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " 23:59:59";
				sQueryTime1 = formatterTime(dtBegin);
				sQueryTime2 = sTimeEnd;
				bQuery = true;
				OpenLoding("1%");
			} else if (dtBegin.getDate() != dtEnd.getDate()) {
				var y = dtBegin.getFullYear();
				var m = dtBegin.getMonth() + 1;
				var d = dtBegin.getDate();
				var sTimeEnd = y + "-" + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " 23:59:59";
				sQueryTime1 = formatterTime(dtBegin);
				sQueryTime2 = sTimeEnd;
				bQuery = true;
				OpenLoding("1%");
			} else {
				bQuery = false;
				sQueryTime1 = formatterTime(dtBegin);
				sQueryTime2 = formatterTime(dtEnd);
				OpenLoding("1%");
				$.ajax({
					url: sUrl + "gethistorydata",
					cache: false,
					type: "get",
					dataType: 'json',
					data: {
						VehID: VehID,
						BeginTime: sQueryTime1,
						EndTime: sQueryTime2,
						Token: sGlobalToken
					},
					success: function(data) {
						if (data.code != 0) {
							if(loadingFlag != undefined){
								layer.close(loadingFlag);
							}
							AjaxErro(ErrCode(arrLang, data.code));
						} else {
							if(loadingFlag != undefined){
								layer.close(loadingFlag);
							}
							if (data.data.length > 0) {
								dataHistory.push(data.data);
							}
						}
						var iCount = 0;
						for (var i = 0; i < dataHistory.length; i++) {
							iCount = iCount + dataHistory[i].length;
						}
						DisabledBtn(false);
						InfoTip(arrLang["QueryFinish"]);
						AddToHistoryTable();
						/* if (iCount > 0) {
							ClearHistoryTable();
							DrawLine();
							return;
						} else {
							ClearHistoryTable();
							clearLine();
						} */
					},
					error: function(e) {
						DisabledBtn(false);
						if(loadingFlag != undefined){
							layer.close(loadingFlag);
						}
						AjaxErro(e.responseText);
					}
				});
				return;
			}

			$.ajax({
				url: sUrl + "gethistorydata",
				cache: false,
				type: "get",
				dataType: 'json',
				data: {
					VehID: VehID,
					BeginTime: sQueryTime1,
					EndTime: sQueryTime2,
					Token: sGlobalToken
				},
				success: function(data) {
					if (data.code == 0) {
						if (data.data.length > 0) {
							dataHistory.push(data.data);
						}
					} else {
						AjaxErro(ErrCode(arrLang, data.code));
					}
					OpenLoding("50%");
					if (bQuery) {
						GetNextHistory();
					}
				},
				error: function(e) {
					bQuery = false;
					DisabledBtn(false);
					if(loadingFlag != undefined){
						layer.close(loadingFlag);
					}
					AjaxErro(e.responseText);
				}
			});
		}
		Query();

		function GetNextHistory() {
			var sUrl = app.getAppUrl().url;
			var sQueryBeginTime = "";
			var sQueryEndTime = "";
			var sUserType = "2";
			//            if(bUserID)
			//            {
			//                sUserType = "1";
			//            }
			var date3 = dtTime2.getTime() - dtTime1.getTime();
			//计算出相差天数
			var days = Math.floor(date3 / (24 * 3600 * 1000));
			var procDay = parseInt(((TotalDay - days) / TotalDay * 100));
			if (procDay == 0) {
				procDay = 1;
			}
			if (dtTime1.getFullYear() != dtTime2.getFullYear()) //年不相同
			{
				var y = dtTime1.getFullYear();
				var m = dtTime1.getMonth() + 1;
				var d = dtTime1.getDate();
				var sTimeEnd = y + "-" + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " 23:59:59";
				sQueryBeginTime = formatterTime(dtTime1);
				sQueryEndTime = sTimeEnd;
				bQuery = true;
				OpenLoding(procDay + "%");
				//            var dtQ = dtTime1;
				//            dtQ.setDate(dtQ.getDate()+1);
			} else if (dtTime1.getMonth() != dtTime2.getMonth()) //月不相同
			{
				var y = dtTime1.getFullYear();
				var m = dtTime1.getMonth() + 1;
				var d = dtTime1.getDate();
				var sTimeEnd = y + "-" + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " 23:59:59";
				sQueryBeginTime = formatterTime(dtTime1);
				sQueryEndTime = sTimeEnd;
				bQuery = true;
				OpenLoding(procDay + "%");
			} else if (dtTime1.getDate() != dtTime2.getDate()) {
				var y = dtTime1.getFullYear();
				var m = dtTime1.getMonth() + 1;
				var d = dtTime1.getDate();
				var sTimeEnd = y + "-" + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " 23:59:59";
				sQueryBeginTime = formatterTime(dtTime1);
				sQueryEndTime = sTimeEnd;
				bQuery = true;
				OpenLoding(procDay + "%");
			} else {
				bQuery = false;
				sQueryBeginTime = formatterTime(dtTime1);
				sQueryEndTime = formatterTime(dtTime2);
				$.ajax({
					url: sUrl + "gethistorydata",
					cache: false,
					type: "get",
					dataType: 'json',
					data: {
						VehID: VehID,
						BeginTime: sQueryBeginTime,
						EndTime: sQueryEndTime,
						Token: sGlobalToken
					},
					success: function(data) {
						if (data.code != 0) {
							if(loadingFlag != undefined){
								layer.close(loadingFlag);
							}
							AjaxErro(ErrCode(arrLang, data.code));
						} else {
							if(loadingFlag != undefined){
								layer.close(loadingFlag);
							}
							if (data.data.length > 0) {
								dataHistory.push(data.data);
							}
						}
						var iCount = 0;
						for (var i = 0; i < dataHistory.length; i++) {
							iCount = iCount + dataHistory[i].length;
						}
						InfoTip(arrLang["QueryFinish"]);
						DisabledBtn(false);
						AddToHistoryTable();
						/* if (iCount > 0) {
							ClearHistoryTable();
							return;
						} else {
							ClearHistoryTable();
							clearLine();
						} */

					},
					error: function(e) {
						bQuery = false;
						DisabledBtn(false);
						if(loadingFlag != undefined){
							layer.close(loadingFlag);
						}
						AjaxErro(e.responseText);
					}
				});
				return;
			}
			dtTime1.setDate(dtTime1.getDate() + 1);
			$.ajax({
				url: sUrl + "gethistorydata",
				cache: false,
				type: "get",
				dataType: 'json',
				data: {
					VehID: VehID,
					BeginTime: sQueryBeginTime,
					EndTime: sQueryEndTime,
					Token: sGlobalToken
				},
				success: function(data) {
					if(loadingFlag != undefined){
						layer.close(loadingFlag);
					}
					if (data.code == 0) {
						if (data.data.length > 0) {
							dataHistory.push(data.data);
						}
					} else {
						AjaxErro(ErrCode(arrLang, data.code));
					}
					if (bQuery) {
						GetNextHistory();
					}
				},
				error: function(e) {
					bQuery = false;
					DisabledBtn(false);
					if(loadingFlag != undefined){
						layer.close(loadingFlag);
					}
					AjaxErro(e.responseText);
				}
			});
		}
	}

	var arrHistoryDatagrid = [];

	function ClearHistoryTable() {
		arrHistoryDatagrid.length = 0;
	}

	function GetComponent(sComponent) {
		var sReturn = "";
		try {
			if (globalSettings["lang"] == "Zh") {
				sReturn = sComponent;
				return sReturn;
			} else if (sComponent != undefined) {
				var bAdd = "";
				var arrComponent = sComponent.split(' ');
				$.each(arrComponent, function(i, value) {
					if (value.length > 3) {
						if (value[0] == 'A' && value[1] == 'D') {
							sReturn = sReturn + bAdd + value;
							bAdd = ";";
							return true;
						}
						if (value[0] == '电' && value[1] == '量') {
							sReturn = sReturn + bAdd + value.replace("电量", arrLang["Battery"]);
							bAdd = ";";
							return true;
						}
						if (value[0] == '点' && value[1] == '火' && value[2] == '时' && value[3] == '定') {
							sReturn = sReturn + bAdd + value.replace("点火时定时间隔", arrLang["RightAccOnTimingInterval"]).replace("秒", arrLang[
								"Second"]);
							bAdd = ";";
							return true;
						}
						if (value[0] == '熄' && value[1] == '火' && value[2] == '时' && value[3] == '定') {
							sReturn = sReturn + bAdd + value.replace("熄火时定时间隔", arrLang["RightAccOffTimingInterval"]).replace("秒", arrLang[
								"Second"]);
							bAdd = ";";
							return true;
						}
						if (value[0] == '运' && value[1] == '动') {
							sReturn = sReturn + bAdd + value.replace("运动模式时长", arrLang["MovementPatternTime"]).replace("分", arrLang[
								"Minute"]);
							bAdd = ";";
							return true;
						}
						if (value[0] == '静' && value[1] == '止') {
							sReturn = sReturn + bAdd + value.replace("静止模式时长", arrLang["StaticModelTime"]).replace("分", arrLang["Minute"]);
							bAdd = ";";
							return true;
						}
						if (value[0] == '已' && value[1] == '发' && value[2] == '条' && value[3] == '数') {
							sReturn = sReturn + bAdd + value.replace("已发条数", arrLang["SendNum"]);
							bAdd = ";";
							return true;
						}
						if (value[0] == '剩' && value[1] == '余' && value[2] == '条' && value[3] == '数') {
							sReturn = sReturn + bAdd + value.replace("剩余条数", arrLang["RemainCount"]);
							bAdd = ";";
							return true;
						}
					}
					switch (value) {
						case "ACC开":
						case "ACC开(启动)":
							sReturn = sReturn + bAdd + arrLang["AccOn"];
							bAdd = ";";
							break;
						case "ACC关":
						case "ACC关(熄火) ":
							sReturn = sReturn + bAdd + arrLang["AccOff"];
							bAdd = ";";
							break;
						case "油路正常":
							sReturn = sReturn + bAdd + arrLang["PowerNormal"];
							bAdd = ";";
							break;
						case "油路断开":
							sReturn = sReturn + bAdd + arrLang["PowerOff"];
							bAdd = ";";
							break;
						case "G_Sensor异常":
							sReturn = sReturn + bAdd + arrLang["G_SensorAnomaly"];
							bAdd = ";";
							break;
						case "G_Sensor正常":
							sReturn = sReturn + bAdd + arrLang["G_SensorNormal"];
							bAdd = ";";
							break;
						case "ACAR蓝牙功能开启":
							sReturn = sReturn + bAdd + arrLang["ACARBluetoothOpen"];
							bAdd = ";";
							break;
						case "ACAR蓝牙功能关闭":
							sReturn = sReturn + bAdd + arrLang["ACARBluetoothClose"];
							bAdd = ";";
							break;
						case "刹车":
							sReturn = sReturn + bAdd + arrLang["Brakes"];
							bAdd = ";";
							break;
						case "未刹车":
							sReturn = sReturn + bAdd + arrLang["NoBrakes"];
							bAdd = ";";
							break;
						case "左转向关":
							sReturn = sReturn + bAdd + arrLang["SteerLeft"] + ";" + arrLang["DoorClose"];
							bAdd = ";";
							break;
						case "左转向开":
							sReturn = sReturn + bAdd + arrLang["SteerLeft"] + ";" + arrLang["DoorOpen"];
							bAdd = ";";
							break;
						case "右转向关":
							sReturn = sReturn + bAdd + arrLang["SteerRight"] + ";" + arrLang["DoorClose"];
							bAdd = ";";
							break;
						case "右转向开":
							sReturn = sReturn + bAdd + arrLang["SteerRight"] + ";" + arrLang["DoorOpen"];
							bAdd = ";";
							break;
						case "远光灯关":
							sReturn = sReturn + bAdd + arrLang["DistanceLight"] + ";" + arrLang["DoorClose"];
							bAdd = ";";
							break;
						case "远光灯开":
							sReturn = sReturn + bAdd + arrLang["DistanceLight"] + ";" + arrLang["DoorOpen"];
							bAdd = ";";
							break;
					}
				});
			}
		} catch (e) {}
		return sReturn;
	}

	function AddToHistoryTable() {
		try {
			arrHistoryDatagrid.length = 0;
			$.each(dataHistory, function(i, value) {
				$.each(value, function(j, valuej) {
					valuej["address"] = "";
					valuej["name"] = $.trim($('#txtHistoryPlate').val());
					if (valuej.Locate == 1) {
						valuej["LocateStr"] = arrLang["Location"];
					} else if (valuej.Locate == 2) {
						valuej["LocateStr"] = arrLang["BasestationLocation"];
					} else {
						valuej["LocateStr"] = arrLang["NotLocating"];
					}
					valuej["speedangle"] = (Array(3).join(0) + valuej.Velocity).slice(-3) + "km/h " + AngleToString(valuej.Angle);
					if (valuej.Velocity == 65534) {
						valuej["speedangle"] = arrLang["Abnormal"];
					} else if (valuej.Velocity == 65535) {
						valuej["speedangle"] = arrLang["Invalid"];
					}
					valuej["Component"] = GetComponent(valuej["Component"]);
					arrHistoryDatagrid.push(valuej);
				});
			});
			if (arrHistoryDatagrid.length == 0) {
				InfoTip(arrLang["NoData"]);
			} else {
				OpenHistoryMap(arrHistoryDatagrid);
			}
		} catch (e) {}
	}

	$('#divHistorySearch').find('.historyTimeBtn').each(function(i, btn) {
		btn.addEventListener('tap', function() {
			var _self = this;
			if (_self.picker) {
				_self.picker.show(function(rs) {
					$(_self).html(rs.text);
					$(_self).attr("data-options", "{\"value\":\"" + rs.text + "\"}");
					_self.picker.dispose();
					_self.picker = null;
				});
			} else {
				var optionsJson = this.getAttribute('data-options') || '{}';
				var options = JSON.parse(optionsJson);
				var id = this.getAttribute('id');
				_self.picker = new mui.DtPicker(options);
				_self.picker.show(function(rs) {
					$(_self).html(rs.text);
					$(_self).attr("data-options", "{\"value\":\"" + rs.text + "\"}");
					_self.picker.dispose();
					_self.picker = null;
				});
			};
			ChangeLan(".mui-dtpicker", arrLang);
		}, false);
	});


	if (id != undefined && id != null) {
		$.each(arrGlobalTerminal, function(i, value) {
			if (value["id"] == id) {
				$('#txtHistoryPlate').attr("tag", value["id"]);
				$('#txtHistoryPlate').val(value["name"]);
			}
		});
		if (bLoadHistorySearchPopover) {
			scrollviewSearch.setSelect(id, true, false);
		}
	}
}

var bLoadHistorySearchPopover = false;

function OpenHistoryPlateSearch() {
	mui("#popoverSearch").popover('toggle', document.getElementById("divSearch"));
	$('#popoverSearch').find(".mui-popover-arrow").hide();
	scrollviewSearch.viewReSize();
	scrollviewSearch.getOptions()["selectChange"] = selectHistoryPlateChange;
	if (!bLoadHistorySearchPopover) {
		var arrTreeData = [];
		$.each(arrGlobalTeam, function(i, value) {
			var rowTree = {};
			rowTree["id"] = value.id;
			rowTree["name"] = value.name;
			rowTree["sim"] = "";
			rowTree["parentid"] = value.PID;
			rowTree["chkshow"] = "hide";
			rowTree["icon"] = "images/gpsicon/team.png";
			arrTreeData.push(rowTree);
		});
		$.each(arrGlobalTerminal, function(i, value) {
			var rowTree = {};
			rowTree["id"] = value["id"];
			rowTree["sim"] = value["sim"];
			rowTree["name"] = value["name"];
			rowTree["parentid"] = value.GID;
			rowTree["icon"] = value["icon"];
			arrTreeData.push(rowTree);
		});
		scrollviewSearch.setData(arrTreeData);
		scrollviewSearch.viewReSize();
		var state = app.getState();
		if (arrGlobalTeam.length > 0 && state.usertype == 2) {
			scrollviewSearch.expand(arrGlobalTeam[0]["id"]);
		}
		bLoadHistorySearchPopover = true;
		var sTag = $('#txtHistoryPlate').attr("tag");
		if (sTag.length > 0) {
			scrollviewSearch.setSelect(sTag, true, false);
		}
	}
}
